package com.rf.richfitwheel.admin.sys.service.impl;

import com.rf.richfitwheel.admin.sys.model.SendEmail;
import com.rf.richfitwheel.admin.sys.service.EmailService;
import com.rf.richfitwheel.admin.sys.util.EmailUtil;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Value("${mail.username}")
    private String userName;
    @Value("${mail.password}")
    private String password;

    /**
     * 发送邮件公共接口
     * @param sendEmail
     * @return
     */
    @Override
    public R sendEmail(SendEmail sendEmail) {
        log.info("sendEmail 接口执行，入参为：{}",sendEmail);
        try {
            /**
             * 默认情况下，在这里输入账号和密码，便可收信与发信
             */
            //判断是否有输入账号
            if (StringUtils.isBlank(sendEmail.getSendUserName())){
                //没有输入则使用默认的
                sendEmail.setSendUserName(userName);
                sendEmail.setSendPass(password);
            }
            EmailUtil eu = new EmailUtil(sendEmail.getSendUserName(), sendEmail.getSendPass());

            EmailUtil sem = new EmailUtil();
            /**
             * 发件人邮箱
             */
            sem.setFrom(sendEmail.getSendEmail());
            /**
             * 收件人邮箱
             */
            sem.setRecipient(sendEmail.getReceiveEmail());
            /**
             * 标题
             */
            sem.setSubject(sendEmail.getTitle());

            /**
             * 内容
             */
            sem.setText(sendEmail.getBody());
            /**
             * 发送邮件
             */
            eu.sendMail(EmailUtil.getSMTP(), sem);
            log.info("发送成功");
            return R.ok("发送成功！");
        }catch (Exception e){
            log.info("发送失败");
            e.printStackTrace();
        }
        return R.error("发送失败！");
    }
}
